package dolf.window;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import dolf.game.Game;
import dolf.game.Level;
import dolf.game.Parcours;
import dolf.game.Player;
import dolf.objects.ImageStore;

public class NewGameWindow extends Window {
	private static NewGameWindow instance = new NewGameWindow();
	private static final long serialVersionUID = 1L;
	private static final int MAXPLAYER = 8;
	private List<Player> players;
	private DefaultListModel  selectedModel = new DefaultListModel();

	private int zeile = 0;
	
	private ArrayList<Color> usedColors = new ArrayList<Color>();
	private Color[] colors = {
			new Color(255,230,0),  //gelb
			new Color(255,160,122), //lachs
			new Color(255,140,10), //orange
			new Color(205,85,85), //hellrot
			new Color(205,38,38), //dunkelrot
			new Color(238,130,238), //hellrosa
			new Color(208,32,144), //pink
			new Color(141,238,238), //hellblau
			new Color(65,105,225), //blau
			new Color(144,238,144), // hellgruen
			new Color(50,205,50), //dunkelgruen
			new Color(189,183,107), //beige
			new Color(139,101,8), //dunkelbraun
			new Color(212,212,212), //hellgraun
			new Color(105,105,105) //dunkelgrau
			};
	

	class lAttr {
		public String name;
		public String path;
		public lAttr(String p) {
			name = getNameFromPath(p);
			path = p;
		}
		public String toString() {
			return name;
		}
	}

	private NewGameWindow() {
		initialize();
	}
	
	private void initialize() {
		initialize(SystemMessagesHandler.getInstance().getMessages().getString("new_game"));
		usedColors.clear();
		players = getPlayerList();
		List<String> parcs = getParcoursList();
		selectedModel.removeAllElements();
		for (String p: parcs) {
			selectedModel.addElement(new lAttr(p));
		}

	}
	public static NewGameWindow getInstance() {
		return instance;
	}

	private void savePlayerList() {
		try {
			java.io.File targetDir =  new java.io.File(System.getProperty("user.home")+java.io.File.separator+".dolf");
			if (!targetDir.exists()) targetDir.mkdir();
			String target =  System.getProperty("user.home")+java.io.File.separator+".dolf"+java.io.File.separator+"players.properties";
			java.io.FileOutputStream stream = new java.io.FileOutputStream(target, false);
			java.util.Properties playerFile = new java.util.Properties();

			if (playerFile == null) {
				System.err.println("ERROR: File players.properties ");
			}
			else {
				playerFile.setProperty("count", Integer.toString(players.size()));

				for (int i = 0; i < players.size(); i++) {
					int color = players.get(i).getColor().getRed() * 256 * 256 +
					players.get(i).getColor().getGreen() * 256 +
					players.get(i).getColor().getBlue();
					playerFile.setProperty("player["+i+"].name", players.get(i).getName());
					playerFile.setProperty("player["+i+"].color", Integer.toString(color));
				}
				playerFile.store(stream, "dolf player file: stores Player when game is started and reverts on load");
				stream.close();
			}

		} catch (IOException e) {
			System.err.println("ERROR: " + e.getMessage());
			e.printStackTrace();
		}
	}
	private void saveParcoursList() {
		/*save current parcourslist to file*/
		try {
			java.io.File targetDir =  new java.io.File(System.getProperty("user.home")+java.io.File.separator+".dolf");
			if (!targetDir.exists()) targetDir.mkdir();
			String target =  System.getProperty("user.home")+java.io.File.separator+".dolf"+java.io.File.separator+"parcours.properties";
			java.io.FileOutputStream stream = new java.io.FileOutputStream(target, false);
			java.util.Properties parcoursFile = new java.util.Properties();

			if (parcoursFile == null) {
				System.err.println("ERROR: File parcours.properties ");
			}
			else {
				Object[] foo = selectedModel.toArray();
				parcoursFile.setProperty("count", Integer.toString(foo.length));

				for (int i = 0; i < foo.length; i++) {
					parcoursFile.setProperty("parcours["+i+"]",((lAttr) foo[i]).path);
				}
				parcoursFile.store(stream, "dolf parcours file: stores Parcours when game is started and reverts on load");
				stream.close();
			}

		} catch (IOException e) {
			System.err.println("ERROR: " + e.getMessage());
			e.printStackTrace();
		}
	}

	/* read player-file
	 * File should look like:
	 * 
	 * count=x
	 * player[0].name=foo
	 * player[0].color=bar
	 * ...
	 * player[x-1].name=foo
	 * player[x-1].color=bar
	 * 
	 * color = int[0-16.777.215]
	 */

	private List<Player> getPlayerList() {
		List<Player> list = new LinkedList<Player>();
		try {
			java.io.InputStream stream = new java.io.FileInputStream(System.getProperty("user.home")+java.io.File.separator+".dolf"+java.io.File.separator+"players.properties");
			java.util.Properties playerFile = new java.util.Properties();

			playerFile.load(stream);

			if (playerFile == null) {
				System.err.println("ERROR: File players.properties ");
			}
			else {
				int count = Integer.parseInt(playerFile.getProperty("count", "0"));
				if (count > MAXPLAYER) count = MAXPLAYER;
				for (int i = 0; i < count; i++) {
					String name = playerFile.getProperty("player["+i+"].name");
					String color = playerFile.getProperty("player["+i+"].color");

					if (name == null || color == null) System.err.println("ERROR: could not parse players.properties");
//					fals farbe nicht gueltig: neue raussuchen (verhindert freie farbwahl ueber configfile
					Color plCol = new Color(Integer.parseInt(color));
					if (!java.util.Arrays.asList(colors).contains(plCol)) {
						System.out.println("color "+plCol+" in properties file not in list, using random one");
						Random rand = new Random();
						while (usedColors.contains(plCol = colors[rand.nextInt(colors.length)] )){};
					}
					usedColors.add(plCol);
					list.add(new Player(name, plCol));
				}
				stream.close();
			}

		} catch (IOException e) {
			System.err.println("ERROR: File players.properties " + e.getMessage());
		}
		return list;

	}
	private List<String> getParcoursList() {
		List<String> list = new LinkedList<String>();
		List<String> avParcs = getAvailableParcours();
		
		try {
			java.io.InputStream stream = new java.io.FileInputStream(System.getProperty("user.home")+java.io.File.separator+".dolf"+java.io.File.separator+"parcours.properties");
			java.util.Properties parcoursFile = new java.util.Properties();

			parcoursFile.load(stream);

			if (parcoursFile == null) {
				System.err.println("ERROR: File parcours.properties ");
			}
			else {
				int count = Integer.parseInt(parcoursFile.getProperty("count", "0"));
				for (int i = 0; i < count; i++) {
					String path = parcoursFile.getProperty("parcours["+i+"]");
					
					if (path == null) System.err.println("ERROR: could not parse parcours.properties");
					else if (!avParcs.contains(path)) System.err.println("ERROR: parcours "+path+" not in parcours.list");
					else list.add(path);
				}
				stream.close();
			}

		} catch (IOException e) {
			System.err.println("ERROR: File parcours.properties " + e.getMessage());
		}
		return list;

	}

	public void draw() {

		getContentPane().removeAll();
		initialize(SystemMessagesHandler.getInstance().getMessages().getString("new_game"));
		initialize();
		
		final List<Player> plList = new LinkedList<Player>(players);

		final JTabbedPane tabPaneV = new JTabbedPane(JTabbedPane.LEFT);
		tabPaneV.setBorder(new EmptyBorder(0,0,10,10));

		final JTabbedPane tabPaneH = new JTabbedPane();
		tabPaneH.setBorder(new EmptyBorder(0,0,10,0));

		final JPanel localPane = new JPanel(new GridBagLayout());
		localPane.setBorder(new EmptyBorder(10,10,10,10));
		localPane.setVisible(true);

		final JPanel networkPane = new JPanel(new GridLayout(0,3));
		networkPane.setBorder(new EmptyBorder(10,10,10,10));
		networkPane.setVisible(true);

		final JButton addButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("add_player"));
		addButton.setMnemonic('a');

		JButton delAllButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("clear_all"));
		delAllButton.setMnemonic('c');

		JButton cancelButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("cancel"));
		cancelButton.setMnemonic('c');

		JButton startButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("start_game"));
		startButton.setMnemonic('s');

		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (tabPaneH.getSelectedIndex() == 0) { //local Player

					final JTextField tf = new JTextField();
					tf.setPreferredSize(new Dimension(150,25));
					tf.setFont(new Font("SansSerif", Font.BOLD , 12));
					JButton ok = new JButton();
					ok.setIcon(new javax.swing.ImageIcon(this.getClass().getClassLoader().getResource("dolf/gfx/window/ok.png")));
				    ok.setContentAreaFilled(false);
					ok.setBorderPainted(false);
					ok.setFocusPainted(false);
					ok.setMargin(new Insets(0,0,0,0));
					ok.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
					
					GridBagConstraints c = new GridBagConstraints();
					c.ipadx = 10;
					c.gridx = 0;
					c.gridy = zeile;
					localPane.add(tf, c);

					c.gridx = 1;
					c.gridy = zeile++;
					localPane.add(ok, c);
					tf.requestFocus();
					addButton.setEnabled(false);
					pack();

					java.util.Random rand = new java.util.Random();
					Color randColor;
					while (usedColors.contains(randColor = colors[rand.nextInt(colors.length)])) {};
					
					final Color col = randColor;
					tf.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e){
							String newname = tf.getText();
							if (!newname.isEmpty()) {
								plList.add(new Player(newname, col));
								usedColors.add(col);
							}
							drawPlayerList(localPane,plList,addButton);
							if (plList.size() < MAXPLAYER) addButton.setEnabled(true); else addButton.setEnabled(false);
						}

					});

					ok.addActionListener(new ActionListener(){

						public void actionPerformed(ActionEvent e) {
							String newname = tf.getText();
							if (!newname.isEmpty()) {
								plList.add(new Player(newname, col));
								usedColors.add(col);
							}
							drawPlayerList(localPane, plList,addButton);
							if (plList.size() < MAXPLAYER) addButton.setEnabled(true); else addButton.setEnabled(false);
						}
					});
					
				} else { //remote Hosts

					final JTextField tf = new JTextField();
					tf.setToolTipText(SystemMessagesHandler.getInstance().getMessages().getString("tooltip_host"));
					JLabel ok = new JLabel(new javax.swing.ImageIcon(this.getClass().getClassLoader().getResource("dolf/gfx/window/ok.png")));
					ok.setCursor(new Cursor(Cursor.HAND_CURSOR));
					addButton.setEnabled(false);

					tf.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e){
							String host = tf.getText();
							InetSocketAddress sock = null;
							try {
								sock = new InetSocketAddress(host, Integer.parseInt(ConfigurationHandler.getInstance().getProperty("port", "2222")));
							}
							catch (IllegalArgumentException ex) {
								tf.setBackground(Color.RED.darker());
							}

							if (!host.isEmpty() && sock != null && !sock.isUnresolved()) {
								tf.setBackground(Color.GREEN.darker());
								if (players.size() < MAXPLAYER) addButton.setEnabled(true); else addButton.setEnabled(false);
							} else {
								tf.setBackground(Color.RED.darker()); 
							}
						}

					});

					networkPane.add(tf);
					networkPane.add(ok);
					tf.requestFocus();
					addButton.setEnabled(false);
				}
			}
		});
		delAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				plList.clear();
				localPane.removeAll();
				if (plList.size() < MAXPLAYER) addButton.setEnabled(true); else addButton.setEnabled(false);
				pack();
				setLocationRelativeTo(MainWindow.getInstance());
			}
		});

		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LinkedList<Parcours> p = new LinkedList<Parcours>();
				try {
					Object[] selected = selectedModel.toArray();
					for (int i = 0; i < selected.length; i++) {
						Class<?> pClass = Class.forName("dolf.game.Parcours");
						Constructor<?> co = pClass.getConstructors()[0];
						final Parcours pa = (Parcours) co.newInstance(((lAttr) selected[i]).path);
						p.add(pa);
					}
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				} catch (IllegalArgumentException e1) {
					e1.printStackTrace();
				} catch (InvocationTargetException e1) {
					e1.printStackTrace();
				}


				if (plList.isEmpty()) {
					JOptionPane.showMessageDialog(instance,
							SystemMessagesHandler.getInstance().getMessages().getString("select_min_one_player"),
							SystemMessagesHandler.getInstance().getMessages().getString("error"),
							JOptionPane.ERROR_MESSAGE);
				} else if (p.isEmpty()) {
					JOptionPane.showMessageDialog(instance,
							SystemMessagesHandler.getInstance().getMessages().getString("select_min_one_level"),
							SystemMessagesHandler.getInstance().getMessages().getString("error"),
							JOptionPane.ERROR_MESSAGE);
				} else {
					players = plList;
					savePlayerList();
					saveParcoursList();
					dispose();

					if (Game.getInstance() != null && Game.getInstance().isStarted()) {
						System.out.println("stopping running game");
						Game.getInstance().stopTimer();
						Level.getInstance().flushLevel();
					}
					Game.initGame(players, p);

					MainWindow.getInstance().getContentPane().removeAll();
					MainWindow.getInstance().getContentPane().add(Canvas.getInstance(), BorderLayout.CENTER);
					MainWindow.getInstance().getContentPane().add(PlayerDisplay.getInstance(), BorderLayout.LINE_END);
					MainWindow.getInstance().getContentPane().add(ScoreDisplay.getInstance(), BorderLayout.PAGE_END);

					MainWindow.getInstance().pack();

					BuyWindow.getInstance().reset();

					ScoreDisplay.getInstance().draw();

					Game.getInstance().startGame();
				}

			}
		});

		drawPlayerList(localPane, plList,addButton);

		JPanel buttonPane = new JPanel();
		buttonPane.setVisible(true);
		buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
		buttonPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

		buttonPane.add(delAllButton,BorderLayout.LINE_START);
		buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
		buttonPane.add(addButton,BorderLayout.CENTER);

		buttonPane.add(Box.createHorizontalGlue());
		buttonPane.add(Box.createRigidArea(new Dimension(20,0)));
		buttonPane.add(cancelButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
		buttonPane.add(startButton,BorderLayout.LINE_END);


		JPanel tmpPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
		tmpPane.add(localPane);
		tabPaneH.add(SystemMessagesHandler.getInstance().getMessages().getString("local_player"),tmpPane);
		//end localPane


		//begin networkPane

		tabPaneH.add(SystemMessagesHandler.getInstance().getMessages().getString("network_player"),networkPane);

		//end networkPane

		//begin levelpane

		//end levelpane


		tabPaneV.add(SystemMessagesHandler.getInstance().getMessages().getString("player"), tabPaneH);
		tabPaneV.add(SystemMessagesHandler.getInstance().getMessages().getString("parcours"), drawParcoursPane());
		add(tabPaneV, BorderLayout.NORTH);
		add(new JSeparator(), BorderLayout.CENTER);
		add(buttonPane, BorderLayout.PAGE_END);

		startButton.requestFocus();

		pack();
		setLocationRelativeTo(MainWindow.getInstance());
		setVisible(true);
	}

	private void drawPlayerList(final JPanel panel,final List<Player> plList, final JButton addButton){
		panel.removeAll();
		if (plList.size() < MAXPLAYER) addButton.setEnabled(true); else addButton.setEnabled(false);
		if (plList != null) { 

			for (final Player pl: plList){
				final JTextField nameLabel = new JTextField(pl.getName());
				nameLabel.setPreferredSize(new Dimension(150,25));
				nameLabel.setFont(new Font("SansSerif", Font.BOLD , 12));
				nameLabel.setForeground(pl.getColor());

				nameLabel.getDocument().addDocumentListener(new DocumentListener() {

					public void changedUpdate(DocumentEvent arg0) {
						pl.setName(nameLabel.getText());
					}

					public void insertUpdate(DocumentEvent arg0) {
						pl.setName(nameLabel.getText());
					}

					public void removeUpdate(DocumentEvent arg0) {
						pl.setName(nameLabel.getText());
					}
				});
				
				JButton delButton = new JButton();
				delButton.setPreferredSize(new Dimension(24,24));
				delButton.setMargin(new Insets(0,0,0,0));
				delButton.setFocusPainted(false);
				delButton.setContentAreaFilled(false);
				delButton.setBorderPainted(false);
				//delButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
				delButton.setIcon(new javax.swing.ImageIcon(this.getClass().getClassLoader().getResource("dolf/gfx/window/del.png")));

				delButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						plList.remove(pl);
						usedColors.remove(pl.getColor());
						drawPlayerList(panel, plList, addButton);
					}
				});
				
				JPanel colorBar = new JPanel();
				ButtonGroup bG = new ButtonGroup();
				
				for (int i = 0; i < colors.length; i++) {
					JButton b = new JButton();
					b.setBackground(colors[i]);
					if (usedColors.contains(colors[i]) && !pl.getColor().equals(colors[i])) {
						b.setEnabled(false);
					}
					b.setOpaque(true);
					b.setPreferredSize(new Dimension(17,17));
					b.setBorderPainted(true);
					b.setMargin(new Insets(2,2,2,2));
					b.setFocusPainted(true);
					
					if (pl.getColor().equals(colors[i])) {
						b.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
					}
					b.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							JButton b = (JButton) e.getSource();
							usedColors.remove(pl.getColor());
							pl.setColor(b.getBackground());
							usedColors.add(pl.getColor());
							drawPlayerList(panel, plList, addButton);
							System.out.println(usedColors.size());
						}
					});
					
					bG.add(b);
					colorBar.add(b);
				}
				
				GridBagConstraints c = new GridBagConstraints();
				c.ipadx = 10;
				c.gridx = 0;
				c.gridy = zeile;
				panel.add(nameLabel, c);

				c.gridx = 1;
				c.gridy = zeile;
				panel.add(delButton, c);
				
				c.gridx = 2;
				c.gridy = zeile++;
				panel.add(colorBar, c);
			}
		}
		pack();
	}
	
	private JPanel drawParcoursPane() {

		JPanel levelPane = new JPanel(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		int line = 0;

		final DefaultListModel listModel = new DefaultListModel();
		final JList list = new JList(listModel);

		final Hashtable<String, LinkedList<lAttr> > mapPackList = getLevelList();
		Object[] mapPacks = mapPackList.keySet().toArray();
		final JComboBox lSelec = new JComboBox(mapPacks);
		lSelec.setPreferredSize(new Dimension(175,25));

		//initialzustand
		lSelec.setSelectedItem(SystemMessagesHandler.getInstance().getMessages().getString("all_maps"));
		listModel.removeAllElements();
		LinkedList<lAttr> maps = mapPackList.get(lSelec.getSelectedItem());
		for (int i = 0; i < maps.size(); i++) {
			listModel.addElement(maps.get(i));
		}
		//aenderung
		lSelec.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				listModel.removeAllElements();
				LinkedList<lAttr> maps = mapPackList.get(lSelec.getSelectedItem());
				for (int i = 0; i < maps.size(); i++) {
					listModel.addElement(maps.get(i));
				}
				list.setSelectedIndex(0);
			}

		});
		c.gridx = 0;
		c.gridy = line;
		levelPane.add(lSelec,c);	
		final JLabel imageL = new JLabel();

		list.addListSelectionListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {
				if (!list.isSelectionEmpty()) {
					String name = ((lAttr) list.getSelectedValue()).path;
					name = name.substring(0, name.lastIndexOf('.'));
					name = name + ".png";
					Image icon = ImageStore.getInstance().getImage(name);
					if (icon == null) {
						icon = ImageStore.getInstance().getImage("dolf/gfx/window/no_preview.png");
						icon = icon.getScaledInstance(140, 105, Image.SCALE_SMOOTH);
					}
					else icon = icon.getScaledInstance(140, 105, Image.SCALE_SMOOTH);
					imageL.setIcon(new ImageIcon(icon));
				}
				else {
					imageL.setIcon(null);
				}
			}

		});

		list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		list.setSelectedIndex(0);
		list.setVisibleRowCount(5);
		JScrollPane listScrollPane = new JScrollPane(list);
		listScrollPane.setPreferredSize(new Dimension(180,150));
		listScrollPane.setBorder(BorderFactory.createTitledBorder(SystemMessagesHandler.getInstance().getMessages().getString("available_maps")));

		c.gridx = 0;
		c.gridheight = 4;
		c.gridy = line+1;
		levelPane.add(listScrollPane,c);
		c.gridheight = 1;

		final JList selectedList = new JList(selectedModel);

		selectedList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		selectedList.setSelectedIndex(0);
		selectedList.setVisibleRowCount(5);
		JScrollPane selectedScrollPane = new JScrollPane(selectedList);
		selectedScrollPane.setPreferredSize(new Dimension(180,180));
		selectedScrollPane.setBorder(BorderFactory.createTitledBorder(SystemMessagesHandler.getInstance().getMessages().getString("selected_maps")));

		c.gridx = 2;
		c.gridy = line;
		c.gridheight = 3;
		levelPane.add(selectedScrollPane,c);
		c.gridheight = 1;


		JButton selectButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("select"));
		selectButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] selected = list.getSelectedValues();
				int pos = 0;
				for (int k = 0; k < selected.length; k++) {
					selectedModel.add(selectedList.getSelectedIndex()+ pos++ +1, selected[k]);
				}
			}

		});
		JButton delButton = new JButton(SystemMessagesHandler.getInstance().getMessages().getString("remove"));
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] selected = selectedList.getSelectedValues();
				for (int k = 0; k < selected.length; k++) {
					selectedModel.removeElement(selected[k]);
				}
			}

		});
		JPanel bP = new JPanel(new GridLayout(0,1));
		JLabel space = new JLabel();
		space.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));
		bP.add(selectButton);
		bP.add(space);
		bP.add(delButton);
		c.gridx = 1;
		c.gridy = line+2;
		levelPane.add(bP,c);


		JPanel imgPane = new JPanel();
		imgPane.setBorder(BorderFactory.createTitledBorder(SystemMessagesHandler.getInstance().getMessages().getString("preview")));
		imgPane.setPreferredSize(new Dimension(150,150));
		imgPane.add(imageL);
		c.gridx = 3;
		c.gridy = line;
		c.gridheight = 4;

		levelPane.add(imgPane,c);

		JPanel f = new JPanel(new FlowLayout(FlowLayout.LEFT));
		f.add(levelPane);
		return f;

	}
	private LinkedList<String> getAvailableParcours() {
		LinkedList<String> parcs = new LinkedList<String>();
		
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					this.getClass().getClassLoader().getResourceAsStream("dolf/game/levels/level.index")));
			String lev = null;
			while ((lev = in.readLine()) != null) {
				if(lev.charAt(0)!='#') {
					parcs.add(lev);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return parcs;
	}
	
	private Hashtable<String, LinkedList<lAttr> > getLevelList() {
		Document doc = XMLHandler.getInstance().getDocument("dolf/game/levels/mappacks.xml", "dolf/game/levels/mappacks.dtd");
		XPath xpath = XPathFactory.newInstance().newXPath();

		Hashtable<String, LinkedList<lAttr> > mapPacks= new Hashtable< String, LinkedList<lAttr>>();

		//search in levels.index for level-files, create list
		LinkedList<String> avParcs = getAvailableParcours();
		for (String lev: avParcs) {
			LinkedList<lAttr> maps = mapPacks.get(SystemMessagesHandler.getInstance().getMessages().getString("all_maps"));
			if (maps == null) {
				mapPacks.put(SystemMessagesHandler.getInstance().getMessages().getString("all_maps"), new LinkedList<lAttr>());
			}
			mapPacks.get(SystemMessagesHandler.getInstance().getMessages().getString("all_maps")).add(new lAttr(lev));
		}
		
		//add other MapPacks to array
		try {
			NodeList packs = (NodeList) xpath.evaluate("/mappacks/mappack", doc, XPathConstants.NODESET);
			for (int i = 0; i < packs.getLength(); i++) {
				String name = (String) xpath.evaluate("@name", packs.item(i), XPathConstants.STRING);
				LinkedList<lAttr> list = new LinkedList<lAttr>();

				NodeList maps = (NodeList) xpath.evaluate("map", packs.item(i), XPathConstants.NODESET);
				if (maps.getLength() != 0) { 

					for (int j = 0; j < maps.getLength(); j++) {
						String path = (String) xpath.evaluate("@path", maps.item(j), XPathConstants.STRING);
						if (avParcs.contains(path)) list.add(new lAttr(path));
					}
					if (list.size() != 0) mapPacks.put(name, list);
				}
			}
		}
		catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return mapPacks;
	}

	private String getNameFromPath(String path) {
		Document doc = XMLHandler.getInstance().getDocument(path, "dolf/game/levels/level.dtd" );
		XPath xpath = XPathFactory.newInstance().newXPath();
		String name = "";
		try {
			name = (String) xpath.evaluate("/level/info/name/text()", doc, XPathConstants.STRING);
		}
		catch (XPathExpressionException e) {
			e.printStackTrace();
		}

		return name;
	}
}
